<template>
    <div class="app-container">
        <!-- 查询区域 -->
        <el-card class="search-card" v-show="showSearch">
            <el-form :model="queryParams">
                <el-row :gutter="20">
                    <el-col :span="4">
                        <el-form-item label="配置名称">
                            <el-input v-model="queryParams.configName" placeholder="请输入配置名称" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="消息类型">
                            <el-select v-model="queryParams.msgType" placeholder="请选择消息类型" clearable
                                style="width: 100%">
                                <el-option label="全部" value="" />
                                <el-option label="短信" :value="0" />
                                <el-option label="邮件" :value="1" />
                                <el-option label="钉钉" :value="2" />
                                <el-option label="企业微信" :value="3" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="推送通道">
                            <el-select v-model="queryParams.channelId" placeholder="请选择推送通道" clearable
                                style="width: 100%">
                                <el-option v-for="item in channelOptions" :key="item.id" :label="item.name"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="启用状态">
                            <el-select v-model="queryParams.enabled" placeholder="请选择状态" clearable style="width: 100%">
                                <el-option label="全部" value="" />
                                <el-option label="启用" :value="1" />
                                <el-option label="停用" :value="0" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" style="text-align: left;">
                        <el-button type="primary" @click="handleQuery">查询</el-button>
                        <el-button @click="resetQuery">重置</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>

        <!-- 操作按钮区域 -->
        <el-card class="table-card">
            <div class="action-buttons">
                <el-button type="success" @click="handleAdd">新增配置</el-button>
            </div>

            <!-- 数据表格 -->
            <el-table :data="tableData" v-loading="loading" @selection-change="handleSelectionChange" border>
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column type="index" label="序号" width="60" align="center" />
                <el-table-column prop="configName" label="配置名称" align="center" min-width="150" show-overflow-tooltip />
                <el-table-column prop="msgType" label="消息类型" align="center" width="100">
                    <template #default="{ row }">
                        <el-tag :type="getMsgTypeTagType(row.msgType)">
                            {{ getMsgTypeName(row.msgType) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="title" label="消息标题" align="center" min-width="150" show-overflow-tooltip />
                <el-table-column prop="receiver" label="接收人" align="center" min-width="120" show-overflow-tooltip />
                <el-table-column prop="messageContent" label="推送内容" align="center" min-width="200"
                    show-overflow-tooltip>
                    <template #default="{ row }">
                        <span class="content-text">{{ row.messageContent || '-' }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="enabled" label="状态" align="center" width="80">
                    <template #default="{ row }">
                        <!-- <el-switch v-model="row.enabled" :active-value="1" :inactive-value="0" 
                @change="handleStatusChange(row)" /> -->
                        <el-tag :type="row.enabled == 1 ? 'success' : 'warning'">{{ row.enabled == 1 ? '启用' : '禁用'
                            }}</el-tag>

                    </template>
                </el-table-column>
                <el-table-column prop="createdAt" label="创建时间" align="center" width="180">
                    <template #default="{ row }">
                        {{ formatDateTime(row.createdAt) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="280" fixed="right">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" @click="handleView(row.id)">查看</el-button>
                        <el-button type="warning" size="small" @click="handleEdit(row)">编辑</el-button>
                        <el-button type="success" size="small" @click="handleTest(row.id)">测试</el-button>
                        <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination">
                <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
                    :total="total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <!-- 新增/编辑对话框 -->
        <el-dialog v-model="dialog.visible" :title="dialog.title" width="900px" :close-on-click-modal="false">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="配置名称" prop="configName">
                            <el-input v-model="form.configName" placeholder="请输入配置名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="消息类型" prop="msgType">
                            <el-select v-model="form.msgType" placeholder="请选择消息类型" style="width: 100%"
                                @change="handleMsgTypeChange">
                                <el-option label="短信" :value="0" />
                                <el-option label="邮件" :value="1" />
                                <el-option label="钉钉" :value="2" />
                                <el-option label="企业微信" :value="3" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="推送通道" prop="channelId">
                            <el-select v-model="form.channelId" placeholder="请选择推送通道" style="width: 100%">
                                <el-option v-for="item in channelOptions" :key="item.id" :label="item.name"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="消息模板" prop="templateId">
                            <el-select v-model="form.templateId" placeholder="请选择消息模板" style="width: 100%"
                                @change="handleTemplateChange">
                                <el-option v-for="item in templateOptions" :key="item.messageTemplateId"
                                    :label="item.messageTemplateName" :value="item.messageTemplateId" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="接收人" prop="receiver">
                            <el-input v-model="form.receiver" :placeholder="getReceiverPlaceholder" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="消息标题" prop="title">
                            <el-input v-model="form.title" placeholder="请输入消息标题" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" v-if="form.msgType === 0">
                        <el-form-item label="短信模板编码" prop="smsCode">
                            <el-input v-model="form.smsCode" placeholder="请输入短信模板编码" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="启用状态">
                            <el-switch v-model="form.enabled" :active-value="1" :inactive-value="0" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 模板参数配置 -->
                <el-form-item label="模板参数" v-if="selectedTemplate && selectedTemplate.messageTemplateContent">
                    <div class="template-preview">
                        <div class="template-header">
                            <span>模板内容：{{ selectedTemplate.messageTemplateContent }}</span>
                        </div>
                        <div class="params-config" v-if="templateParams.length > 0">
                            <div class="params-title">参数配置：</div>
                            <el-row :gutter="20">
                                <el-col :span="24" v-for="(param, index) in templateParams" :key="index">
                                    <el-form-item :label="param" style="margin-top: 10px;">
                                        <el-input v-model="form.params[param]" :placeholder="`请输入${param}的值`"
                                             />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </div>
                        <div class="preview-area" v-if="form.msgType !== 0">
                            <div class="preview-title">消息预览：</div>
                            <el-input v-model="previewContent" type="textarea" :rows="3" readonly
                                style="width: 100%;" />
                        </div>
                    </div>
                </el-form-item>

                <el-form-item label="备注">
                    <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" maxlength="200"
                        show-word-limit />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialog.visible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">确定</el-button>
            </template>
        </el-dialog>

        <!-- 查看详情对话框 -->
        <el-dialog v-model="detailDialog.visible" title="配置详情" width="800px">
            <el-descriptions v-if="detailData" :column="2" border>
                <el-descriptions-item label="配置ID">{{ detailData.id }}</el-descriptions-item>
                <el-descriptions-item label="配置名称">{{ detailData.configName }}</el-descriptions-item>
                <el-descriptions-item label="消息类型">
                    <el-tag :type="getMsgTypeTagType(detailData.msgType)">
                        {{ getMsgTypeName(detailData.msgType) }}
                    </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="推送通道">{{ getChannelName(detailData.channelId) }}</el-descriptions-item>
                <el-descriptions-item label="消息模板">{{ getTemplateName(detailData.templateId) }}</el-descriptions-item>
                <el-descriptions-item label="接收人">{{ detailData.receiver }}</el-descriptions-item>
                <el-descriptions-item label="消息标题">{{ detailData.title }}</el-descriptions-item>
                <el-descriptions-item label="短信模板编码" v-if="detailData.msgType === 0">{{ detailData.smsCode || '无'
                    }}</el-descriptions-item>
                <el-descriptions-item label="启用状态">
                    <el-tag :type="detailData.enabled === 1 ? 'success' : 'danger'">
                        {{ detailData.enabled === 1 ? '启用' : '停用' }}
                    </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="模板参数" :span="2">
                    <pre class="detail-pre">{{ detailData.paramVal || '无' }}</pre>
                </el-descriptions-item>
                <el-descriptions-item label="模板内容" :span="2">
                    <pre class="detail-pre">{{ detailData.templateValue || '无' }}</pre>
                </el-descriptions-item>
                <el-descriptions-item label="推送内容" :span="2">
                    <pre class="detail-pre">{{ detailData.messageContent || '无' }}</pre>
                </el-descriptions-item>
                <el-descriptions-item label="备注">{{ detailData.remark || '无' }}</el-descriptions-item>
                <el-descriptions-item label="创建人">{{ detailData.createdBy }}</el-descriptions-item>
                <el-descriptions-item label="创建时间">{{ formatDateTime(detailData.createdAt) }}</el-descriptions-item>
                <el-descriptions-item label="更新时间">{{ formatDateTime(detailData.updatedAt) }}</el-descriptions-item>
            </el-descriptions>
            <template #footer>
                <el-button @click="detailDialog.visible = false">关闭</el-button>
                <el-button type="primary" @click="handleTest(detailData.id)">测试配置</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'

// API导入
import {
    getMessageTypeDictListV2,
    getChannelTypeDictList,
    getAppPushConfigList,
    getAppPushConfigDetail,
    addAppPushConfig,
    updateAppPushConfig,
    deleteAppPushConfig,
    testAppPushConfig
} from '@/api/basic/message/push'

const showSearch = ref(true)

// 查询参数
const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    configName: '',
    msgType: '',
    channelId: '',
    enabled: ''
})

// 表单数据
const form = reactive({
    id: undefined,
    configName: '',
    msgType: '',
    channelId: '',
    templateId: '',
    params: {},
    enabled: 1,
    receiver: '',
    smsCode: '',
    title: '',
    remark: ''
})

// 对话框控制
const dialog = reactive({
    visible: false,
    title: '新增配置',
    isEdit: false
})

const detailDialog = reactive({
    visible: false
})

// 表格数据
const tableData = ref([])
const channelOptions = ref([])
const templateOptions = ref([])
const total = ref(0)
const loading = ref(false)
const selectedRows = ref([])
const formRef = ref()
const detailData = ref(null)
const selectedTemplate = ref(null)
const templateParams = ref([])
const previewContent = ref('')

// 表单验证规则
const rules = reactive({
    configName: [
        { required: true, message: '请输入配置名称', trigger: 'blur' }
    ],
    msgType: [
        { required: true, message: '请选择消息类型', trigger: 'change' }
    ],
    channelId: [
        { required: true, message: '请选择推送通道', trigger: 'change' }
    ],
    templateId: [
        { required: true, message: '请选择消息模板', trigger: 'change' }
    ],
    receiver: [
        { required: true, message: '请输入接收人', trigger: 'blur' }
    ],
    title: [
        { required: true, message: '请输入消息标题', trigger: 'blur' }
    ]
})

// 计算属性
const getReceiverPlaceholder = computed(() => {
    const placeholders = {
        0: '请输入手机号码',
        1: '请输入邮箱地址',
        2: '请输入钉钉用户ID',
        3: '请输入企业微信用户ID'
    }
    return placeholders[form.msgType] || '请输入接收人'
})

// 初始化数据
onMounted(() => {
    getList()
})

// 获取APP推送配置列表
const getList = async () => {
    try {
        loading.value = true
        const res = await getAppPushConfigList(queryParams)
        tableData.value = res.rows || []
        total.value = res.total || 0
    } catch (error) {
        console.error('获取配置列表失败:', error)
        ElMessage.error('获取配置列表失败')
    } finally {
        loading.value = false
    }
}

// 查询处理
const handleQuery = () => {
    queryParams.pageNum = 1
    getList()
}

// 重置查询
const resetQuery = () => {
    Object.assign(queryParams, {
        pageNum: 1,
        configName: '',
        msgType: '',
        channelId: '',
        enabled: ''
    })
    getList()
}

// 分页处理
const handleSizeChange = (size) => {
    queryParams.pageSize = size
    getList()
}

const handleCurrentChange = (page) => {
    queryParams.pageNum = page
    getList()
}

// 表格选择变化
const handleSelectionChange = (selection) => {
    selectedRows.value = selection
}

// 新增配置
const handleAdd = async () => {
    dialog.title = '新增配置'
    dialog.isEdit = false
    resetForm()
    dialog.visible = true
}

// 编辑配置
const handleEdit = async (row) => {
    try {
        const res = await getAppPushConfigDetail(row.id)
        if (res.data) {
            Object.assign(form, {
                id: res.data.id,
                configName: res.data.configName,
                msgType: res.data.msgType,
                channelId: res.data.channelId,
                templateId: res.data.templateId,
                params: res.data.paramVal ? JSON.parse(res.data.paramVal) : {},
                enabled: res.data.enabled,
                receiver: res.data.receiver,
                smsCode: res.data.smsCode,
                title: res.data.title,
                remark: res.data.remark
            })

            // 加载模板和通道数据
            await loadTemplateAndChannelData(res.data.msgType)
            dialog.title = '编辑配置'
            dialog.isEdit = true
            dialog.visible = true
        }
    } catch (error) {
        console.error('获取配置详情失败:', error)
        ElMessage.error('获取配置详情失败')
    }
}

// 查看详情
const handleView = async (id) => {
    try {
        const res = await getAppPushConfigDetail(id)
        detailData.value = res.data
        detailDialog.visible = true
    } catch (error) {
        console.error('获取配置详情失败:', error)
        ElMessage.error('获取配置详情失败')
    }
}

// 测试配置
const handleTest = async (configId) => {
    try {
        await ElMessageBox.confirm('确定要测试此配置吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        await testAppPushConfig(configId)
        ElMessage.success('测试请求已发送，请查看接收端是否收到消息')
    } catch (error) {
        if (error !== 'cancel') {
            console.error('测试配置失败:', error)
            ElMessage.error('测试配置失败')
        }
    }
}

// 测试表单配置
const handleTestForm = async () => {
    try {
        await formRef.value.validate()

        await ElMessageBox.confirm('确定要测试此配置吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        // 这里需要先保存配置再测试，或者调用测试接口
        ElMessage.info('请先保存配置再进行测试')
    } catch (error) {
        if (error !== 'cancel') {
            console.error('测试配置失败:', error)
        }
    }
}

// 删除配置
const handleDelete = (row) => {
    ElMessageBox.confirm(`确定要删除配置"${row.configName}"吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            await deleteAppPushConfig(row.id)
            ElMessage.success('删除成功')
            getList()
        } catch (error) {
            console.error('删除失败:', error)
            ElMessage.error('删除失败')
        }
    }).catch(() => { })
}

// 批量删除
const handleBatchDelete = () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要删除的记录')
        return
    }

    const ids = selectedRows.value.map(item => item.id)
    ElMessageBox.confirm(`确定要删除选中的${ids.length}条记录吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            await deleteAppPushConfig(ids.join(','))
            ElMessage.success('批量删除成功')
            selectedRows.value = []
            getList()
        } catch (error) {
            console.error('批量删除失败:', error)
            ElMessage.error('批量删除失败')
        }
    }).catch(() => { })
}

// 批量启用
const handleBatchEnable = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要启用的记录')
        return
    }

    try {
        for (const row of selectedRows.value) {
            await updateAppPushConfig({
                ...row,
                enabled: 1
            })
        }
        ElMessage.success('批量启用成功')
        getList()
    } catch (error) {
        console.error('批量启用失败:', error)
        ElMessage.error('批量启用失败')
    }
}

// 批量停用
const handleBatchDisable = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要停用的记录')
        return
    }

    try {
        for (const row of selectedRows.value) {
            await updateAppPushConfig({
                ...row,
                enabled: 0
            })
        }
        ElMessage.success('批量停用成功')
        getList()
    } catch (error) {
        console.error('批量停用失败:', error)
        ElMessage.error('批量停用失败')
    }
}

// 状态切换
const handleStatusChange = async (row) => {
    try {
        await updateAppPushConfig({
            id: row.id,
            enabled: row.enabled
        })
        ElMessage.success(row.enabled === 1 ? '启用成功' : '停用成功')
    } catch (error) {
        console.error('状态切换失败:', error)
        // 恢复原状态
        row.enabled = row.enabled === 1 ? 0 : 1
        ElMessage.error('状态切换失败')
    }
}

// 消息类型变化处理
const handleMsgTypeChange = async (msgType) => {
    form.channelId = ''
    form.templateId = ''
    templateParams.value = []
    selectedTemplate.value = null

    await loadTemplateAndChannelData(msgType)
}

// 加载模板和通道数据
const loadTemplateAndChannelData = async (msgType) => {
    try {
        const [templateRes, channelRes] = await Promise.all([
            getMessageTypeDictListV2(msgType),
            getChannelTypeDictList(msgType)
        ])

        templateOptions.value = templateRes.data || []
        channelOptions.value = channelRes.data || []
    } catch (error) {
        console.error('加载数据失败:', error)
        ElMessage.error('加载数据失败')
    }
}

// 模板变化处理
const handleTemplateChange = (templateId) => {
    if (!templateId) {
        selectedTemplate.value = null
        templateParams.value = []
        return
    }

    const template = templateOptions.value.find(item => item.messageTemplateId === templateId)
    if (template) {
        selectedTemplate.value = template
        console.log(selectedTemplate.value);
        form.smsCode = template.messageTemplateContent;
        // 提取模板参数
        extractTemplateParams(template.messageTemplateContent)
    }
}

// 提取模板参数
const extractTemplateParams = (content) => {
    if (!content) {
        templateParams.value = []
        return
    }

    // 使用正则表达式提取 #{参数名} 格式的参数
    const paramRegex = /#\{([^}]+)\}/g
    const matches = content.matchAll(paramRegex)
    const params = []

    for (const match of matches) {
        const paramName = match[1]
        if (!params.includes(paramName)) {
            params.push(paramName)
        }
    }

    templateParams.value = params

    // 初始化参数对象
    const newParams = {}
    params.forEach(param => {
        newParams[param] = form.params[param] || ''
    })
    form.params = newParams

    // 更新预览
    updatePreview()
}

// 更新预览内容
const updatePreview = () => {
    if (!selectedTemplate.value) {
        previewContent.value = ''
        return
    }

    let preview = selectedTemplate.value.messageTemplateContent

    templateParams.value.forEach(param => {
        const value = form.params[param] || `#{${param}}`
        preview = preview.replace(new RegExp(`#\\{${param}\\}`, 'g'), value)
    })

    previewContent.value = preview
}

// 监听参数变化，实时更新预览
watch(() => form.params, () => {
    updatePreview()
}, { deep: true })

// 重置表单
const resetForm = () => {
    if (formRef.value) {
        formRef.value.clearValidate()
    }
    Object.assign(form, {
        id: undefined,
        configName: '',
        msgType: '',
        channelId: '',
        templateId: '',
        params: {},
        enabled: 1,
        receiver: '',
        smsCode: '',
        title: '',
        remark: ''
    })
    selectedTemplate.value = null
    templateParams.value = []
    previewContent.value = ''
}

// 提交表单
const submitForm = async () => {
    try {
        await formRef.value.validate()

        const submitData = {
            ...form,
            params: form.params
        }

        if (dialog.isEdit) {
            await updateAppPushConfig(submitData)
            ElMessage.success('更新成功')
        } else {
            await addAppPushConfig(submitData)
            ElMessage.success('新增成功')
        }

        dialog.visible = false
        getList()
    } catch (error) {
        console.error('提交失败:', error)
    }
}

// 工具函数
const formatDateTime = (dateTime) => {
    if (!dateTime) return '-'
    return dayjs(dateTime).format('YYYY-MM-DD HH:mm:ss')
}

const getMsgTypeName = (type) => {
    const typeMap = {
        0: '短信',
        1: '邮件',
        2: '钉钉',
        3: '企业微信'
    }
    return typeMap[type] || '未知类型'
}

const getMsgTypeTagType = (type) => {
    const typeMap = {
        0: 'success',
        1: 'primary',
        2: 'warning',
        3: 'info'
    }
    return typeMap[type] || 'info'
}

const getChannelName = (channelId) => {
    const channel = channelOptions.value.find(item => item.id === channelId)
    return channel ? channel.name : '未知通道'
}

const getTemplateName = (templateId) => {
    const template = templateOptions.value.find(item => item.messageTemplateId === templateId)
    return template ? template.messageTemplateName : '未知模板'
}
</script>

<style scoped>
.app-container {
    padding: 20px;
}

.search-card {
    margin-bottom: 20px;
}

.table-card {
    margin-bottom: 20px;
}

.action-buttons {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
}

.pagination {
    margin-top: 20px;
    text-align: right;
}

.content-text {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
}

.template-preview {
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 16px;
    background-color: #f8f9fa;
}

.template-header {
    font-weight: 500;
    margin-bottom: 12px;
    color: #606266;
}

.params-config {
    margin-top: 16px;
}

.params-title {
    font-weight: 500;
    margin-bottom: 12px;
    color: #606266;
}

.preview-area {
    margin-top: 16px;
}

.preview-title {
    font-weight: 500;
    margin-bottom: 8px;
    color: #606266;
}

.detail-pre {
    white-space: pre-wrap;
    word-break: break-all;
    margin: 0;
    font-family: inherit;
    line-height: 1.5;
}
</style>